package com.han.spider.contact;

import com.han.util.UnZipper;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class HuaweiContactManager {

    private final HttpClient httpClient;
    private final HttpRequest.Builder requestBuilder;
    private String csrfToken;

    private HuaweiContactManager(String csrfToken) {
        HttpClient.Builder clientBuilder = HttpClient.newBuilder();
        httpClient = clientBuilder.build();

        String cookie = "_dmpa_id=75086f9bddf2b95ef447552950611586507447189.1586507392.1.1586507392.1586507392; _dmpa_ref=%5B%22%22%2C%22%22%2C1586507448%2C%22https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3Ds3cpsoOzE9mfMs0bj20LETcnUuY1phuCL4qqninsWXg1Kyo1Nng3-w-r-iuL43bmFLF_ISIRwEiq4UJifvtDua%26wd%3D%26eqid%3De221903100001438000000065e902eaf%22%5D; HW_id_hicloudportal_2_cloud_huawei_com=d9df3fa209364112a13e3b6cb9fb81cd; HW_idts_hicloudportal_2_cloud_huawei_com=1586914320085; HW_idn_hicloudportal_2_cloud_huawei_com=ff504016a1c74eb6857218c877792e39; HuaweiID_CAS_ISCASLOGIN=true; CASLOGINSITE=1; LOGINACCSITE=1; siteID=1; JSESSIONID=D75EBC87F223FB7D7E9246D72D2579A8; loginID=D75EBC87F223FB7D7E9246D72D2579A8; token=e77d00985d9534470d25ca3094ffc056d69e27c1700a5cf7; d377d72df97c4183a234968b9ca517a1=WyI4MzA2NzczOTQiXQ; cplang=en-gb; isLogin=1; loginSecLevel=2; functionSupport=1_1; logId=530b7dab90620b58-2e9a57d884ff18a0; HW_refts_hicloudportal_2_cloud_huawei_com=1586914335481; HW_viewts_hicloudportal_2_cloud_huawei_com=1586914881560; HW_idvc_hicloudportal_2_cloud_huawei_com=7";

        requestBuilder = HttpRequest.newBuilder()
                .timeout(Duration.ofMinutes(1))
                .setHeader("Accept", "application/json, text/plain, */*")
                .setHeader("Accept-Encoding", "gzip, deflate, br")
                .setHeader("Accept-Language", "en,zh-CN;q=0.9,zh;q=0.8")
                .setHeader("Content-Type", "application/json;charset=UTF-8")
                .setHeader("Cookie", cookie + csrfToken)
                .setHeader("CSRFToken", csrfToken)
                .setHeader("DNT", "1")
                .setHeader("Origin", "https://cloud.huawei.com")
                .setHeader("Referer", "https://cloud.huawei.com/home")
                .setHeader("Sec-Fetch-Dest", "empty")
                .setHeader("Sec-Fetch-Mode", "cors")
                .setHeader("Sec-Fetch-Site", "same-origin")
                .setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36")
                .setHeader("userId", "40086000020216937");
    }

    /**
     * 创建单个联系人
     *
     * @param contact 联系人
     * @return 创建结果
     * @throws IOException          异常
     * @throws InterruptedException 异常
     */
    private String create(Contact contact) throws IOException, InterruptedException {

        HttpRequest.BodyPublisher postData = HttpRequest.BodyPublishers.ofString("{\"contact\":{\"contactId\":\"\",\"uId\":\"\",\"groupIdList\":[],\"name\":{\"firstName\":\"" + contact.getName() + "\",\"middleName\":\"\",\"lastName\":\"\",\"namePrefix\":\"\",\"nameSuffix\":\"\"},\"organizeList\":[{\"org\":\"" + contact.getOrg() + "\",\"title\":\"" + contact.getTitle() + "\"}],\"addressList\":[],\"emailList\":[],\"msgList\":[],\"telList\":[{\"type\":1,\"value\":\"" + contact.getPhone_Num() + "\",\"name\":\"\"}],\"urlList\":[],\"eventList\":[],\"bDay\":\"\",\"bDayLunar\":\"\",\"nickName\":\"\",\"note\":\"\",\"photoUrl\":\"\",\"groupName\":[]},\"traceId\":\"03112_02_1586850989_68285423\"}");
        HttpRequest httpRequest = requestBuilder
                .uri(URI.create("https://cloud.huawei.com/contact/createContact"))
                .POST(postData)
                .build();

        HttpResponse<byte[]> byteResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofByteArray());
        String backMsg = new String(UnZipper.unGzipByBytes(byteResponse.body()), StandardCharsets.UTF_8);
        try {
            Optional<String> setCookieStr = byteResponse.headers().firstValue("Set-Cookie");
            csrfToken = setCookieStr.orElse("") + ";";
            csrfToken = csrfToken.substring(csrfToken.indexOf("CSRFToken=") + 10);
            csrfToken = csrfToken.substring(0, csrfToken.indexOf(";"));
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("创建失败:" + backMsg);
        }

        return backMsg;
    }

    /**
     * 批量创建联系人
     */
    private void batchCreate(List<Contact> contactList) {


        for (Contact contact : contactList) {
            String contactStr = contact.toString();
            Status backStatus = new Status();
            try {
                String backMsg = create(contact);
                backStatus = judgeStatus(backMsg);
                Thread.sleep(1000);
            } catch (IOException | InterruptedException e) {
                System.out.println(contactStr + "写入失败:" + e.getMessage());
                backStatus.setSuccess(false);
                backStatus.setDesc(e.getMessage());
            } finally {
                contact.setStatus(backStatus);
            }
        }
    }

    /**
     * 解析返回字符串，解析返回状态
     *
     * @param backMsg 返回字符串
     * @return 状态
     */
    private Status judgeStatus(String backMsg) {
        try {
            JSONObject jsonObject = new JSONObject(backMsg);
            JSONObject resultJson = jsonObject.getJSONObject("result");
            String resultCode = resultJson.getString("resultCode");
            String desc = resultJson.getString("resultDesc");
            return new Status("0".equals(resultCode), desc);
        } catch (JSONException e) {
            System.out.println("解析返回值失败:" + backMsg);
            return new Status(false, "解析失败:" + backMsg);
        }
    }

    /**
     * 填充联系人
     *
     * @param contactStringList 联系人字符串list
     * @return 联系人List
     */
    private List<Contact> fillContactList(List<String> contactStringList) {
        List<Contact> contactList = new ArrayList<>();
        for (String ct : contactStringList) {
            String[] contactStr = ct.split(",");
            Contact contact = new Contact(contactStr[0], contactStr[1], contactStr[2], contactStr[3]);
            contactList.add(contact);
        }
        return contactList;
    }
}
